package com.uhylab.uhuvinetest.service;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

import com.uhylab.uhuvinetest.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;

/**
 * 项目名称：Uhylab
 * 类描述：
 * 创建人：xyb
 * 创建时间：16/8/26 11:16
 * 修改人：xyb
 * 修改时间：16/8/26 11:16
 * 修改备注：
 */
public class UHUpdateService extends Service {
    private static final int NOTIFI_ID = 1000;
    private int preProgress = 0;
    /**
     * 目标文件储存的文件名
     */
    private String destFileName;
    private Context mContext;
    private String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
            + "UHy";
    private NotificationCompat.Builder builder;
    private NotificationManager mNotificationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            mContext = this;
            destFileName = intent.getStringExtra("appName");
            loadFile(intent.getStringExtra("apkUrl"));
        } catch (Exception e) {

        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void loadFile(String apkUrl) {
        initNotification();
        OkHttpUtils.get()
                .url(apkUrl)
                .build()
                .execute(new MyFileCallback(destFileDir, destFileName));

    }

    private void initNotification() {
        builder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("0%")
                .setContentTitle("优壹尿液检查更新")
                .setProgress(100, 0, false);
        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NOTIFI_ID, builder.build());
    }


    private class MyFileCallback extends FileCallBack {

        public MyFileCallback(String destFileDir, String destFileName) {
            super(destFileDir, destFileName);
        }

        /**
         * 下载失败的方法
         *
         * @param call
         * @param e
         * @param id
         */
        @Override
        public void onError(Call call, Exception e, int id) {
            cancelNotification();

        }

        /**
         * 下载完成方法
         *
         * @param response 文件目录
         * @param id
         */
        @Override
        public void onResponse(File response, int id) {
            cancelNotification();
            installApk(response);
        }

        /**
         * 下载进度方法
         *
         * @param progress
         * @param total
         * @param id
         */
        @Override
        public void inProgress(float progress, long total, int id) {
            updateNotification((long) progress * 100);

        }
    }

    /**
     * 更新进度条
     * @param progress
     */
    private void updateNotification(long progress) {
        int nowProgress = (int) progress;
        if (preProgress < nowProgress) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, (int) progress, false);
            mNotificationManager.notify(NOTIFI_ID, builder.build());
        }
        preProgress = (int) progress;


    }

    /**
     * 安装apk方法
     */
    private void installApk(File appFiles) {
        Uri apkUri = Uri.fromFile(appFiles);
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        // 执行安装意图
        mContext.startActivity(install);
    }

    /**
     * 清除notification标题提示
     */
    private void cancelNotification() {
        mNotificationManager.cancel(NOTIFI_ID);

    }
}
